package com.ailanyin.modules.file.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ailanyin.common.base.result.AjaxResult;
import com.ailanyin.common.security.utils.SecurityUtil;
import com.ailanyin.modules.file.domain.SysFile;
import com.ailanyin.modules.file.mapper.SysFileMapper;
import com.ailanyin.modules.file.service.SysFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;
import java.util.List;

/**
 * @author ailanyin
 * @version 1.0
 * @since 2022-09-22 11:17:58
 */
@Service
public class SysFileServiceImpl implements SysFileService {


    @Autowired
    private HttpServletRequest request;

    @Value("${ailanyin.uploadPath}")
    private String path;

    @Resource
    private SysFileMapper sysFileMapper;

    @Override
    public List<SysFile> getListByParam(SysFile sysFile) {
        return sysFileMapper.selectList(sysFile);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertSysFile(SysFile sysFile) {
        sysFile.setUploadTime(new Date());
        sysFileMapper.insertSelective(sysFile);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSysFile(SysFile sysFile) {
        sysFileMapper.updateByPrimaryKeySelective(sysFile);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByIds(List<Long> ids) {
        ids.forEach(this::deleteFile);
        sysFileMapper.deleteByIds(ids);
    }

    @Override
    public SysFile getInfo(Long id) {
        return sysFileMapper.selectByPrimaryKey(id);
    }

    @Override
    public AjaxResult upload(MultipartFile file) {
        String extension = com.ailanyin.modules.file.utils.FileUtil.getExtension(file);
        String filename = file.getOriginalFilename();
        String mimeType = FileUtil.getMimeType(filename);
        // 日期 + 格式 分类
        String dir = DateUtil.format(new Date(), "yyyy/MM/dd") + "/" + extension + "/";
        String downloadUrl = com.ailanyin.modules.file.utils.FileUtil.upload(file, request, path, dir);
        String loginUsername = SecurityUtil.getLoginUsername();
        ThreadUtil.execAsync(() -> insertSysFile(createSysFile(extension, filename, mimeType, dir, downloadUrl, loginUsername)));

        AjaxResult ajax = AjaxResult.success();
        ajax.put("url" , downloadUrl);
        ajax.put("fileName" , filename);
        return ajax;
    }

    private SysFile createSysFile(String extension, String filename, String mimeType, String dir, String downloadUrl, String username) {
        SysFile sysFile = new SysFile();
        sysFile.setFileName(filename);
        sysFile.setUploadTime(new Date());
        sysFile.setDownloadUrl(downloadUrl);
        sysFile.setFileType(extension);
        sysFile.setMimeType(mimeType);
        sysFile.setInDirectory(path + dir);
        sysFile.setUploadUser(username);
        return sysFile;
    }

    private void deleteFile(Long fileId) {
        SysFile info = getInfo(fileId);
        if (ObjectUtil.isNotEmpty(info)) {
            String str = info.getDownloadUrl();
            String path = info.getInDirectory() + str.substring(str.lastIndexOf("/") + 1);
            new File(path).delete();
        }
    }
}
